package com.syx.system.Service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.syx.commoncore.Model.Result;
import com.syx.commoncore.Model.TableDataInfoResult;
import com.syx.commoncore.enums.Resultcode;
import com.syx.security.Exception.ServiceException;
import com.syx.security.Service.TokenService;
import com.syx.system.Manager.UserCacheManager;
import com.syx.system.Mapper.user.UserMapper;
import com.syx.system.Model.user.DTO.UserQueryDTO;
import com.syx.system.Model.user.DTO.UserUpdateStatusDTO;
import com.syx.system.Model.user.User;
import com.syx.system.Model.user.VO.UserVO;
import com.syx.system.Service.IUserService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements IUserService {
    @Resource
    UserMapper userMapper;

    @Value("${jwt.secret}")
    private String secret;

    @Resource
    TokenService tokenService;

    @Resource
    UserCacheManager userCacheManager;




    @Override
    public TableDataInfoResult list(UserQueryDTO userQueryDTO) {
        if (userQueryDTO.getPageNum()==null|| userQueryDTO.getPageSize()==null){
            userQueryDTO.setPageNum(1);
            userQueryDTO.setPageSize(10);
        }
        PageHelper.startPage(userQueryDTO.getPageNum(),userQueryDTO.getPageSize());

        List<UserVO> userVOS = userMapper.selectUserList(userQueryDTO);
        if (userVOS==null || userVOS.isEmpty()){
            return TableDataInfoResult.empty();
        }

        return TableDataInfoResult.success(userVOS,new PageInfo<>(userVOS).getTotal());

    }

    @Override
    public Result<Void> updateStatus(UserUpdateStatusDTO userUpdateStatusDTO,String token) {
        //前端有bug传错了
        User user = userMapper.selectById(userUpdateStatusDTO.getUserId());
        if (user==null){
            throw new ServiceException(Resultcode.FAILED_USER_NOT_EXISTS);
        }
        user.setStatus(userUpdateStatusDTO.getStatus());
        int row = userMapper.updateById(user);
        if (row==0){
            throw new ServiceException(Resultcode.FAILED);
        }
        userCacheManager.refreshUser(user);
        return Result.success();
        //查看redis中谁否有status，有的话修改redis和数据库中同时拉黑，如果没有只修改数据库


    }
}
